package iv1201project.controller;

import iv1201project.model.*;
import java.sql.Date;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;

/**
 * Class for handling database-connection relating to an applicant submitting an application.
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Stateless
public class ApplicantDAO {
    
    @PersistenceContext(unitName = "IV1201ProjectPU")
    private EntityManager em;
    
    /**
     * Persists an application in the database.
     * @param applicant The applicant to be added to the database.
     */
    @Logthis
    public void addApplicant(ApplicantDTO applicant) {
        Person person = new Person();
        
        person.setName(applicant.getName());
        person.setSurname(applicant.getSurname());
        person.setEmail(applicant.getEmail());
        
        Role role = new Role();
        role.setRole_id(2);
        
        List<Availability> availabilityList = new ArrayList<Availability>();
        Availability availability = new Availability();
        availability.setFrom_date(Date.valueOf(applicant.getFromDateAvail().get(0)));
        availability.setTo_date(Date.valueOf(applicant.getToDateAvail().get(0)));
        availabilityList.add(availability);
        
        List<CompetenceProfile> cProfileList = new ArrayList<CompetenceProfile>();
        CompetenceProfile cp = new CompetenceProfile();
        cp.setYears_of_experience(applicant.getYearsOfExp().get(0));
        cp.setCompetence(applicant.getAreaOfExp().get(0));
        cProfileList.add(cp);
        
        person.setCompetenceProfile(cProfileList);
        person.setAvailability(availabilityList);
        person.setRole_id(role);
        
        em.persist(person);
    }
    
    /**
     * Fetches a list of competences.
     * @return A list with competences.
     */
    public List getComptence() {
        Query result = em.createNativeQuery("SELECT competence_id, name FROM competence", Competence.class);
        List<Competence> resultList = result.getResultList();
        return resultList;
    }
}
